package com.mischa.doedeljas.client.ui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JComponent;

import com.mischa.doedeljas.Card;

public class CardButton extends JComponent implements MouseListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2951972913679711188L;
	private Card card;
	private Image image;
	private ActionListener actionListener;

	public CardButton(Card card) throws IOException {
		this.card = card;
		loadImage();
		this.addMouseListener(this);
	}
	
	public void setActionListener(ActionListener listener)
	{
		this.actionListener = listener;
	}
	
	public Card getCard()
	{
		return card;
	}

	private void loadImage() throws IOException
	{
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		String resourceName = this.getClass().getPackage().getName()
			.replace(".ui", "")
			.concat(".images.cards.")			
			.replace(".", "/")
			.concat(getImageName())
			.concat(".png");
		
		InputStream input = classLoader.getResourceAsStream(resourceName);
		image = ImageIO.read(input);		
	}
	
	private String getImageName()
	{
		String[] suits = new String[] { "S", "C", "D", "H" };
		String[] values = new String[] { "7", "8", "9", "10", "J", "Q", "K", "A" };
		
		int suitValue = card.getSuit().toInteger() / 10 - 1;
		int cardValue = card.getValue().toInteger() - 1;
		
		return suits[suitValue].concat(values[cardValue]);		
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		
		g.drawImage(image, 0, 0, this);		
	}
	
	@Override
	public Dimension getMinimumSize() {
		return new Dimension(image.getWidth(this), image.getHeight(this));		
	}
	
	@Override
	public Dimension getPreferredSize() {
		return getMinimumSize();
	}
	
	@Override
	public Dimension getMaximumSize() {
		return getMinimumSize();
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if(actionListener == null)
		{
			return;
		}
		
		if(e.getButton() == MouseEvent.BUTTON1)
		{			
			ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "");
			actionListener.actionPerformed(actionEvent);
		}
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	
	}
}
